use serde::{Deserialize, Serialize};
use std::time::SystemTime;
use std::collections::HashMap;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Member {
    pub id: String,
    pub host: String,
    pub port: u16,
    pub status: MemberStatus,
    pub last_heartbeat: SystemTime,
    pub role: Option<String>,
    pub metadata: HashMap<String, String>,
}

impl Member {
    /// 创建一个新的成员
    pub fn new(id: String, host: String, port: u16) -> Self {
        Self {
            id,
            host,
            port,
            status: MemberStatus::Alive,
            last_heartbeat: SystemTime::now(),
            role: None,
            metadata: HashMap::new(),
        }
    }
    
    /// 设置成员的角色
    pub fn with_role(mut self, role: &str) -> Self {
        self.role = Some(role.to_string());
        self
    }
    
    /// 设置成员的元数据
    pub fn with_metadata(mut self, key: &str, value: &str) -> Self {
        self.metadata.insert(key.to_string(), value.to_string());
        self
    }
    
    /// 获取成员的角色
    pub fn get_role(&self) -> Option<&String> {
        self.role.as_ref()
    }
    
    /// 获取元数据值
    pub fn get_metadata(&self, key: &str) -> Option<&String> {
        self.metadata.get(key)
    }
    
    /// 检查成员是否活跃
    pub fn is_active(&self) -> bool {
        self.status == MemberStatus::Alive
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum MemberStatus {
    Alive,
    Unreachable,
    Down,
    Left,
}

#[derive(Debug, Clone)]
pub enum MembershipEvent {
    MemberJoined(MemberJoined),
    MemberLeft(MemberLeft),
    MemberUnreachable(MemberUnreachable),
    MemberDown(MemberDown),
}

#[derive(Debug, Clone)]
pub struct MemberJoined {
    pub member: Member,
}

#[derive(Debug, Clone)]
pub struct MemberLeft {
    pub member: Member,
}

#[derive(Debug, Clone)]
pub struct MemberUnreachable {
    pub member: Member,
}

#[derive(Debug, Clone)]
pub struct MemberDown {
    pub member: Member,
} 